//
//  WebViewController.swift
//  MECollege
//
//  Created by 马康旭 on 2017/8/24.
//  Copyright © 2017年 马康旭. All rights reserved.
//

import UIKit
import WebKit

let Mobile = "Mobile"

class WebViewController: UIViewController {

    fileprivate lazy var web: WKWebView = {[unowned self] in
        
        let w = WKWebView(frame: CGRect.init(x: 0, y: 0, width: screenWidth, height: screenHeight))
        
        w.uiDelegate = self
        w.navigationDelegate = self
        
        
        let configuration = w.configuration
        
        let hander = ScriptMessageHandler()
        
        hander.delegate = self
        //设置响应js事件的处理对象
        configuration.userContentController.add(hander, name: Mobile)
    
        
        let param = [1,2,3,4,5]
        
        //向网页注入一个用户脚本，点击rightIten时响应
        let script = WKUserScript(source: "function callJavaScript() {passAnArray(\(param));}", injectionTime: .atDocumentEnd, forMainFrameOnly: true)
        
        configuration.userContentController.addUserScript(script)
        
        return w
    }()
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        navigationController?.setNavigationBarHidden(false, animated: true)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(web)
    
        //测试数据
        guard let path = Bundle.main.path(forResource: "wkHtml", ofType: "html") else{return}
        
        let url = URL.init(fileURLWithPath: path)
        
        web.loadFileURL(url, allowingReadAccessTo: url)
        
        navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "ToWeb", style: .plain, target: self, action: #selector(rightClick(item:)))
        
    }
    
    //传递一个数组给web
    @objc func rightClick(item: UIBarButtonItem) -> Void {
        
        //调用的JS方法，执行（注入脚本时，已指定该方法）
        let js = "callJavaScript()";
        
        //闭包处理js不通过的问题，并不是js代码的回调
        web.evaluateJavaScript(js) { (object, error) in
            
            
        }
    }
    
    deinit {
        //清除桥接文件
        web.configuration.userContentController.removeScriptMessageHandler(forName: Mobile)
        //清除所有注入的脚本
        web.configuration.userContentController.removeAllUserScripts()
    }

}

//MARK:- 导航代理事件
extension WebViewController: WKNavigationDelegate{
    // 页面开始加载时调用
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        

    }
    // 当内容开始返回时调用
    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
        
        
    }
    
    // 页面加载完成之后调用
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        
        title = webView.title
    }
    
    // 页面加载失败时调用
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        
    }
    
    //页面跳转的3种
    
    // 接收到服务器跳转请求之后调用
    func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
        
    }
    
//    // 在收到响应后，决定是否跳转
//    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
//        
//    }
//    // 在发送请求之前，决定是否跳转
//    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
//        
//    }
}


//MARK:- UI代理事件
extension WebViewController: WKUIDelegate{
    
    func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
        
        showAlert(title: "Alert框", message: message)
        
        completionHandler()
    }
    
    func showAlert(title: String, message: String) -> Void {
        
        let action = UIAlertAction(title: "好的", style: .cancel, handler: nil)
        
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        
        alert.addAction(action)
        
        present(alert, animated: true, completion: nil)
    }
    
}

//MARK:- UI代理事件
extension WebViewController: WKScriptMessageHandler{
    
    //响应handler处理的事件
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        
        guard message.name == Mobile else {
            print("不是绑定的响应对象")
            return
        }
        
        let dic = message.body as! Dictionary<String, Any>
        
        let title = dic["message"] as! String
        let message = dic["param"]
        
        showAlert(title: title, message: "\(message ?? "no Parameter")")
    }
}
